﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAQ.Common
{
    static class BasicUtil
    {
        /// <summary>  
        /// 截取字节数组  
        /// </summary>  
        /// <param name="srcBytes">要截取的字节数组</param>  
        /// <param name="startIndex">开始截取位置的索引</param>  
        /// <param name="length">要截取的字节长度</param>  
        /// <returns>截取后的字节数组</returns>  
        public static byte[] SubByte(this byte[] srcBytes, int startIndex, int length)
        {
            System.IO.MemoryStream bufferStream = new System.IO.MemoryStream();
            byte[] returnByte = new byte[] { };
            if (srcBytes == null) { return returnByte; }
            if (startIndex < 0) { startIndex = 0; }
            if (startIndex < srcBytes.Length)
            {
                if (length < 1 || length > srcBytes.Length - startIndex) { length = srcBytes.Length - startIndex; }
                bufferStream.Write(srcBytes, startIndex, length);
                returnByte = bufferStream.ToArray();
                bufferStream.SetLength(0);
                bufferStream.Position = 0;
            }
            bufferStream.Close();
            bufferStream.Dispose();
            return returnByte;
        }

        public static int BytesToInteger(this byte[] srcBytes)
        {
            int Value = 0;
            if (srcBytes != null && srcBytes.Length > 0)
            {
                 for(int i=0;i<srcBytes.Length;i++)
                {
                    Value += srcBytes[i] << (8 * i);
                }
            }
            return Value;
        }
        /// <summary>
        /// 添加CheckSum
        /// </summary>
        /// <param name="buffer">buffer without checksum</param>
        /// <returns>buffer with checksum</returns>
        public static byte[] AppendChecksum(params byte[] buffer)
        {
            byte[] temp = new byte[buffer.Length + 2];
            int a = buffer.Sum(t => t);
            Array.Copy(buffer, temp, buffer.Length);
            temp[buffer.Length] = (byte)(a & 0xff);
            temp[buffer.Length + 1] = (byte)((a & 0xff00) >> 8);
            return temp;
        }
        /// <summary>
        /// Verify the Checksum
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static bool VerifyChecksum(this  byte[] buffer)
        {
            byte[] temp = buffer.SubByte(0, buffer.Length - 2);
            int a = temp.Sum(t => t);
            byte a1 = (byte)(a & 0xff);
            byte a2 = (byte)((a & 0xff00) >> 8);
            if(buffer[buffer.Length-1]==a2&&buffer[buffer.Length-2]==a1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
